package cn.lg.soar.system.auth.service;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.system.auth.entity.RoleMenu;
import cn.lg.soar.system.auth.mapper.RoleMenuMapper;
import cn.lg.soar.system.config.AuthCacheKey;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * @date 2022/4/10
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class RoleMenuService extends ServiceImpl<RoleMenuMapper, RoleMenu> {

    /**
     * 根据角色获取菜单id
     * @param roleId
     * @return
     */
    @Cacheable(value = AuthCacheKey.MENU_ID_BY_ROLE, key = "#roleId", cacheManager = "remote")
    public List<Long> getMenuIds(Long roleId) {
        return listObjs(
                Wrappers.<RoleMenu>lambdaQuery()
                        .select(RoleMenu::getMenuId)
                        .eq(RoleMenu::getRoleId, roleId),
                x -> Long.parseLong(x.toString())
        );
    }

    /**
     * 设置角色菜单
     * @param roleId
     * @param menuIds
     */
    @CacheEvict(value = {AuthCacheKey.MENU_ID_BY_ROLE, AuthCacheKey.PERMIT_CODE_BY_ROLE}, key = "#roleId")
    @Transactional(rollbackFor = RuntimeException.class)
    public void setRoleMenu(Long roleId, Collection<Long> menuIds) {
        // 清空旧值
        clearByRole(roleId);
        // 批量保存新值
        if (CollectionUtils.isEmpty(menuIds)) {
            return;
        }
        // 转换
        List<RoleMenu> collect = menuIds.stream()
                .distinct()
                .map(x -> {
                    RoleMenu data = new RoleMenu();
                    data.setMenuId(x);
                    data.setRoleId(roleId);
                    return data;
                })
                .collect(Collectors.toList());
        AssertUtil.isTrue(saveBatch(collect), "保存角色菜单失败");
    }

    @CacheEvict(value = {AuthCacheKey.MENU_ID_BY_ROLE, AuthCacheKey.PERMIT_CODE_BY_ROLE}, key = "#roleId")
    public void clearByRole(Long roleId) {
        this.remove(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, roleId));
    }

    public void clearByMenu(Long menuId) {
        this.remove(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getMenuId, menuId));
    }

}
